package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
)

var message = make(chan string,20)
var world string
func main() {
	conn, err := net.Dial("tcp", "0.0.0.0:8888")
	if err != nil {
		log.Fatal("faile to connect!")
	}
	functionSelect(conn)
}
func functionSelect(conn net.Conn)  {
	fmt.Println("尊敬的用户,请输入您的匿名")
	write()
	writeServer(conn,world)
	for {
		fmt.Println("欢迎登录,尊敬的" + world + ",请问您需要什么服务呢?\n" +
			"1.公共聊天\n" +
			"2.私聊\n" +
			"3.退出登录")
		write()
		if world == "1" {
			fmt.Println("输入quit即可退出该服务哦")
			for {
				Select1(conn)
			}
		} else if world == "2" {
		writeServer(conn,"private")
		fmt.Println("请输入您想私聊人的名字")
		write()
		writeServer(conn,world)
		for{
			Select1(conn)
		}
		} else if world == "3" {
			conn.Close()
			return
		} else {
			fmt.Println("，要被玩坏了!请输入1-3之内的数字哦")
		}
	}

}
func write(){
	for {
		reader := bufio.NewReader(os.Stdin)
		line, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("Failed to read string, err ===", err)
		}
		line = strings.Trim(line, " \r\n")
		if line == "quit" {
			return
		}
		world = line
		return
	}
}
func writeServer(conn net.Conn,line string)  {
	_, err := conn.Write([]byte(line))
	if err != nil {
		fmt.Println("Failed to write conn, err ====", err)
	}
}
func listen(conn net.Conn) {
	buf := make([]byte, 1024)
	n, err := conn.Read(buf)
	if err != nil {
		log.Fatal("faile to read!", err)
	}
		fmt.Println(string(buf[:n]))
}
func Select1(conn net.Conn)  {
	go listen(conn)
	write()
	writeServer(conn,world)
}

